package com.bayss.web.mock.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * User: helen
 * Email: helen@yinyuetai.com
 * Time: 2016/2/17.
 */
public class AnnotationUtil {

    private static Map<Class, Map<Field, Annotation[]>> valueMap = new HashMap<Class, Map<Field, Annotation[]>>();

    private static Set<String> notContain = new HashSet<String>();

    private static AnnotationUtil ourInstance = new AnnotationUtil();

    public static AnnotationUtil getInstance() {
        return ourInstance;
    }

    private AnnotationUtil() {
        Method[] methods = Annotation.class.getDeclaredMethods();

        for (Method method : methods) {
            notContain.add(method.getName());
        }
    }

    public static Map<Field, Annotation[]> getClassAnnotationValues(Class clazz) {

        if (clazz == null) {
            return null;
        }

        Map<Field, Annotation[]> annotationValues = valueMap.get(clazz);

        if (annotationValues == null || annotationValues.isEmpty()) {
            annotationValues = new HashMap<Field, Annotation[]>();

            //获取域的数组
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                Annotation[] annotations = field.getDeclaredAnnotations();
                annotationValues.put(field, annotations);
//                if(annotations.length > 0){
//                }
            }

            valueMap.put(clazz, annotationValues);
        }

        return annotationValues;
    }

    public static Map<String, Object> getAnnotationValues(Annotation annotation) {
        Class clazz = annotation.getClass();
        Method[] methods = clazz.getDeclaredMethods();
        Map<String, Object> values = new HashMap<String, Object>();

        String methodName = null;
        for (Method method : methods) {
            methodName = method.getName();
            if (!notContain.contains(methodName)) {
                Object value = null;
                try {
                    value = method.invoke(annotation, null);
                    values.put(methodName, value);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return values;
    }

    public static Annotation[] getClassAnnotations(Class clazz) {
        if (clazz == null) {
            return null;
        }

        return clazz.getAnnotations();
    }

}

